package com.fotkidemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;
import com.fotkidemo.util.DiskCache;

/**
 * Created with IntelliJ IDEA.
 * User: roma
 * Date: 6/28/12
 * Time: 3:14 AM
 * To change this template use File | Settings | File Templates.
 */
public class ImageDetailActivity extends FragmentActivity {
    public static final String EXTRA_URL = "extra_url";
    public static final String EXTRA_IMAGE = "extra_image";
    public static final String ALBUM_CACHE = "album_cache";
    public static final String IMAGE_COUNT = "image_count";

    private DiskCache diskCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_detail_pager);

        final String url = getIntent().getStringExtra(EXTRA_URL);
        final String album_cache = getIntent().getStringExtra(ALBUM_CACHE);
        final int imageCount = getIntent().getIntExtra(IMAGE_COUNT, 0);
        if (url != null && album_cache != null) {
            diskCache = DiskCache.initAndCreate(this, album_cache);
            ImagePagerAdapter adapter = new ImagePagerAdapter(getSupportFragmentManager(), imageCount, url);
            ViewPager pager = (ViewPager) findViewById(R.id.pager);
            pager.setAdapter(adapter);

            final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
            if (extraCurrentItem != -1) {
                pager.setCurrentItem(extraCurrentItem);
            }
        }
    }

    public DiskCache getDiskCache() {
        return diskCache;
    }

    private class ImagePagerAdapter extends FragmentStatePagerAdapter {
        private final int mSize;
        private String URL;

        public ImagePagerAdapter(FragmentManager fm, int size, String url) {
            super(fm);
            mSize = size;
            URL = url;
        }

        @Override
        public int getCount() {
            return mSize;
        }

        @Override
        public Fragment getItem(int position) {
            return ImageDetailFragment.newInstance(position, URL);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            final ImageDetailFragment fragment = (ImageDetailFragment) object;
            fragment.cancelWork();
            super.destroyItem(container, position, object);
        }
    }
}
